import { HomeAction, HomeInitState } from '@/types/store'

const initValue: HomeInitState = {
  userChannels: [],
  allChannels: [],
  active: 0,
  channelArticles: {},
}
const home = (preState = initValue, action: HomeAction): HomeInitState => {
  switch (action.type) {
    case 'home/getUserChannels':
      return {
        ...preState,
        userChannels: action.payload,
      }
    case 'home/getAllChannels':
      return {
        ...preState,
        allChannels: action.payload,
      }
    case 'home/changeActive':
      return {
        ...preState,
        active: action.payload,
      }
    case 'home/saveChannelsArticle': {
      const { channel_id, timestamp, articles } = action.payload
      const old = preState.channelArticles[channel_id]?.articles || []
      return {
        ...preState,
        channelArticles: {
          //需要追加数据
          ...preState.channelArticles,
          [channel_id]: {
            timestamp,
            articles: [...old, ...articles],
          },
        },
      }
    }
    case 'home/refreshChannelsArticle': {
      const { channel_id, timestamp, articles } = action.payload
      return {
        ...preState,
        channelArticles: {
          //需要追加数据
          ...preState.channelArticles,
          [channel_id]: {
            timestamp,
            articles: [...articles],
          },
        },
      }
    }
    default:
      return preState
  }
}

export default home
